<template>
	<el-dialog title="改变角色" :visible.sync="showDialog" :before-close="cancel" width="499px">
		<el-form :model="userInfo" status-icon :rules="pwdRules" ref="form" label-width="66px">
			<el-form-item label="角色" :rules="userInfo.userRoleRules" prop="role">
				<el-select v-model="userInfo.role" placeholder="请选择角色" style="width: 100%">
					<el-option v-for="item in roleList" :key="item.id" :label="item.name" :value="item.id"> {{ item.name }} </el-option>
				</el-select>
			</el-form-item>
		</el-form>
		<div class="btns">
			<el-button @click="cancel">取消</el-button>
			<el-button @click="confirm" type="primary">确认</el-button>
		</div>
	</el-dialog>
</template>

<script>
import { changeAccountRole } from '../../../api/api';

export default {
	components: {},
	props: {
		show: {
			type: Boolean,
			default: false
		},
		userId: {
			type: String,
			default: ''
		},
		role: {
			type: Object,
			default: () => {}
		},
		roleList: {
			type: Array,
			default: () => []
		}
	},
	data() {
		return {
			userInfo: {
				role: '',
				userRoleRules: [{ required: true, message: '请选择角色', trigger: ['blur', 'change'] }]
			},
			showDialog: false
		};
	},
	watch: {
		show(newVal) {
			// 修改角色中屏蔽“超级管理员”“机器人坐席”两种角色。
			this.showDialog = newVal;
		},
		role(newVal) {
			// 修改角色中屏蔽“超级管理员”“机器人坐席” “管理员” 角色。
			if (newVal) {
				this.userInfo.role = newVal.roleId || '';
			}
		}
	},
	computed: {},
	mounted() {
		console.log('update role', this.role, this.roleList);
	},
	methods: {
		cancel() {
			this.showDialog = false;
			this.userInfo.role = '';
			this.$refs.form && this.$refs.form.resetFields();
			this.$emit('close');
		},
		confirm() {
			this.$refs['form'].validate(valid => {
				if (valid) {
					changeAccountRole(this.userId, this.userInfo.role)
						.then(() => {
							this.$message.success('角色设置成功');
							this.$emit('change', { userId: this.userId, role: this.userInfo.role });
						})
						.catch(err => {
							this.$Spin.hide();
							this.$requestApiError(err, () => {
								this.$router.push('/');
							});
							this.$emit('close');
						});

					this.showDialog = false;
					this.$refs.form.resetFields();
				}
			});
		}
	}
};
</script>

<style lang="less">
.account {
	.btns {
		text-align: right;
	}
	.head {
		padding: 20px 0;
	}
	.el-avatar > img {
		width: 100%;
	}
}
</style>
